#!python
# -*- coding: utf-8 -*-
import pymysql
import traceback
#from cgi import parse_qs
#from cgi import FieldStorage
import json
import base64
#from string import Template
import time
import os
from Crypto.Cipher import ARC4
from Crypto import Random
import socket
import StringIO
import urlparse
import urllib
from flask import Flask
from flask import request
from flask import render_template
from flask import g
from flask import make_response
from flask import jsonify
from flask import redirect
from flask import url_for
from functools import wraps

app = application = Flask(__name__)

random_fp = Random.new()

cookie_key="dea3212fasdf323afasf"

def rc4(key, data):
    r = ARC4.new(key)
    d = r.encrypt(data)
    return d

def connect_db(host, user, passwd, db):
    conn = pymysql.connect(host,
            user, passwd, db, charset="utf8", use_unicode=True)
    return conn

def get_db():
    if hasattr(app,"_dbconn1"):
        try:
            check_db_connection(app._dbconn1)
            return app._dbconn1
        except:
            app._dbconn1.close()
    app._dbconn1 = connect_db("www.simicloud.com","video","MuM5Z9rbdc4MrUeT","video")
    return app._dbconn1

def get_db2():
    if hasattr(app,"_dbconn2"):
        try:
            check_db_connection(app._dbconn2)
            return app._dbconn2
        except:
            app._dbconn2.close()
    app._dbconn2 = connect_db("www.simicloud.com","opensips","opensipsrw.","opensips")
    return app._dbconn2

def check_db_connection(conn):
    cur = conn.cursor()
    cur.execute("select 1+1 from dual where 0 > 1")
    cur.fetchall()
    cur.close()
    try:
        conn.commit()
    except:
        pass

class login_required(object):
    def __init__(self, *args, **kargs):
        if kargs.has_key("next"):
            self.next_p = kargs["next"]
        else:
            self.next_p = "push"
        self.app_arg = {}

    def need_login(self):
        return redirect("%s?next=%s" % (url_for("login"), url_for(self.next_p, **self.app_arg)))

    def __call__(self, fn):
        @wraps(fn)
        def check_login(*args, **kargs):
            if kargs:
                self.app_arg = kargs
            if is_login():
                return fn(*args, **kargs)
            else:
                return self.need_login()
        return check_login

@app.route("/list", methods = ["GET", "POST"])
def get_list():
    conn=get_db()

    args = request.values

    start = int(args.get("start", 0))
    count = int(args.get("count", 10))

    # output
    output = args.get("output", "json")

    # download_url
    download_url = args.get("download_url", u"")

    # movie_name
    movie_name = args.get("movie_name", u"")

    # catalog
    catalog=args.get("catalog", u"")

    # encrypted name
    enc_name = args.get("enc_name", u"")

    # sql
    sql = u"""select id, origin_name, description, download_url, img_url,
        catalog, artist, year, movie_name, location, director, upload_time
        from video """

    if movie_name:
        sql += u"where movie_name = '%s' and download_url is not null limit %d,%d" % (pymysql.escape_string(movie_name), start, count)
    elif enc_name:
        sql += u"where current_name = '%s'" % (enc_name,)
    elif download_url:
        sql +=  u"where download_url = '%s'" % pymysql.escape_string(download_url)
    elif catalog:
        sql += u"where catalog = '%s' and download_url is not null order by upload_time desc limit %d,%d" % (pymysql.escape_string(catalog), start, count)
    else:
        sql += u"where download_url is not null order by upload_time desc limit %d, %d" % (start, count)

    cur = conn.cursor()
    cur.execute(sql)
    result = cur.fetchall()
    cur.close()

    data = []
    num_rows = 0
    for row in result:
        num_rows += 1
        data.append(
                    dict(
                        name = row[1],
                        img_url=row[4],
                        description = row[2],
                        download_link = row[3],
                        movie_name  = row[8],
                        artist = row[6],
                        catalog = row[5],
                        year = int(row[7]) if row[7] else 0,
                        location = row[9],
                        director = row[10],
                        update_time = row[11].strftime("%Y-%m-%d"),
                        num = num_rows,
                        id = row[0],
                    )
                )

    if output == "json":
        return json.dumps(data),200,{"Content-Type":"application/json"}
    elif output == "html":
        mov =  u""
        if movie_name:
            mov = u"&movie_name=%s" % movie_name

        return render_template("movie_list.html", movies = data, 
                next_start = start +count, m_arg = mov, count = count)

    return "bad arguments", 400


@app.route("/edit/<id>", methods = ["GET", "POST"])
@login_required(next="edit_item")
def edit_item(id=0):
    #conn= db.connect()
    id = int(id)
    if request.method == "GET":
        #id = request.args.get("id", 0)
        #try:
        #    id = int(id)
        #except:
        #    return "Bad request", 400

        referer = request.headers.get("referer", '')
        if id == 0:
            cur.close()
            return "Not found", 404

        conn = get_db()
        cur = conn.cursor()
        cur.execute(u"""select origin_name, img_url, description, movie_name, catalog, artist, year, location, director
                from video where id = %d order by upload_time desc""" % id)
        res=  cur.fetchone()
        if not res:
            cur.close()
            return "this id is not exists"

        t = dict(
            origin_name = res[0] if res[0] else "unknow movie",
            id = id,

            img_url = res[1] if res[1] else "",
            desc = res[2] if res[2] else "",
            movie_name = res[3] if res[3] else "",
            catalog = res[4] if res[4] else "",
            artist = res[5] if res[5] else "",
            year = res[6] if res[6] else "",
            referer = referer if referer else "",
            location = res[7] if res[7] else "",
            director = res[8] if res[8] else ""
        )

        cur.close()

        return render_template("edit_movie_info.html", **t)

    elif request.method == "POST":
        #id = request.form.get("id", 0)
        if id == 0:
            return "bad request", 400

        origin_name = request.form.get("origin_name", u"")
        img_url = request.form.get("img_url", u"")
        desc = request.form.get("desc", u"")
        movie_name = request.form.get("movie_name", u"")
        catalog=request.form.get("catalog", u"")
        artist=request.form.get("artist", u"")
        try:
            year = int(request.form.get("year", 0))
        except:
            year = 0
        return_url = request.form.get("return_url", u"")
        location = request.form.get("location", u"")
        director = request.form.get("director", u"")
        sql = u"""update video set origin_name='{origin_name}', img_url='{img_url}',
                description='{desc}', movie_name='{movie_name}', catalog='{catalog}',
                artist='{artist}', year={year}, location='{location}', director='{director}'
                where id={id}
                """ .format (**dict(
                    origin_name = pymysql.escape_string(origin_name),
                    img_url = pymysql.escape_string(img_url),
                    desc = pymysql.escape_string(desc),
                    movie_name = pymysql.escape_string(movie_name),
                    catalog = pymysql.escape_string(catalog),
                    artist = pymysql.escape_string(artist),
                    year = year,
                    id = id,
                    location = pymysql.escape_string(location),
                    director = pymysql.escape_string(director),
                )
           )
        conn = get_db()
        cur = conn.cursor()
        cur.execute(sql)
        conn.commit()
        cur.close()
        if return_url:
            return "",302,{"Location":return_url}
        return '<p>change ok</p><p><a href="%s">Next</a>' % (url_for("edit_item",id=int(id) + 1),)

@app.route("/info", methods=["GET", "POST"])
def info():
    rc4_key = "pnNYugersZ1jyhgPohyBFdg9"

    if request.method == "GET":
        return "ok"

    d2 = request.get_json(force = True, cache = False)

    userinfo=d2["userInfo"]
    statis = d2["statisticsInfo"]

    if not userinfo.has_key("terminalId"):
        return "400 missing some key", 400

    tmp_ui = {}
    tmp_st = {}

    for k,v in userinfo.items():
        if isinstance(v, str) or isinstance(v, unicode):
            v = pymysql.escape_string(v)

        tmp_ui[k] = v

    for k,v in statis.items():
        if isinstance(v, str) or isinstance(v, unicode):
            v = pymysql.escape_string(v)

        tmp_st[k] = v

    userinfo = tmp_ui
    statis = tmp_st

    if not statis.has_key("baiduLiveness"):
        statis["baiduLiveness"] = 0

    if not statis.has_key("musicDuration"):
        statis["musicDuration"] = 0

    if not statis.has_key("openByOther"):
        statis["openByOther"] = 0

    if not userinfo.has_key("deviceId"):
        userinfo["deviceId"] = ""

    if not userinfo.has_key("baiduAccount"):
        userinfo["baiduAccount"] = ""

    if not userinfo.has_key("storageTotal"):
        userinfo["storageTotal"] = 0

    if not userinfo.has_key("storageFree"):
        userinfo["storageFree"] = 0

    is_test = int(d2.get("test", 0))

    if is_test:
        user_tbl = u"t_userinfo"
        mtime_tbl = u"t_mediatimes"
        mname_tbl = u"t_movienames"
    else:
        user_tbl = u"userinfo"
        mtime_tbl = u"mediatimes"
        mname_tbl = u"movienames"

    #conn = db.connect()
    conn = get_db()
    cur = conn.cursor()
    sql = u"""select id from {user_tbl}
    where
        terminalid='{terminalId}'
        and deviceid='{deviceId}'
    """
    s = sql.format(user_tbl=user_tbl, **userinfo)
    #print s
    cur.execute(s)
    rs = cur.fetchall()
    n_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))

    userinfo["last_update"] = n_time
    statis["last_update"] = n_time

    # no record
    if len(rs) == 0:
        sql = u"""insert into {user_tbl} (terminalid, deviceid, terminaltype,terminalversion,clientversion,
                firmwareversion,baiduaccount,last_update,createdate, storagetotal, storagefree
                )
               values(
                    '{terminalId}','{deviceId}','{terminalType}','{terminalVersion}','{clientVersion}',
                    '{firmwareVersion}','{baiduAccount}','{last_update}','{createdate}', {storageTotal}, {storageFree}
                    )
                    """
        s = sql.format(user_tbl = user_tbl, createdate=n_time, **userinfo)
        #print s
        cur.execute(s)
        conn.commit()
    else:
        # has record, check if version is changed
        sql = u"""select id from {user_tbl}
        where
            terminalid='{terminalId}'
            and deviceid = '{deviceId}'
            and terminalversion='{terminalVersion}'
            and clientversion = '{clientVersion}'
            and firmwareversion='{firmwareVersion}'
            and baiduaccount = '{baiduAccount}'
        """
        s = sql.format(user_tbl=user_tbl, **userinfo)
        cur.execute(s)
        rs = cur.fetchall()

        # version is changed
        if len(rs) == 0:
            sql = u"""update {user_tbl} set
                terminalversion='{terminalVersion}',
                clientversion='{clientVersion}',
                baiduaccount='{baiduAccount}',
                firmwareversion='{firmwareVersion}',
                last_update='{last_update}'
            where
                terminalid='{terminalId}'
                and deviceid='{deviceId}'
                """
            s = sql.format(user_tbl=user_tbl, **userinfo)
            cur.execute(s)
            conn.commit()


    m=[]
    m_cols=[]
    m_values=[]

    if int(statis["pictureDuration"]):
        m.append("picturetime=picturetime+%d" % (int(statis["pictureDuration"]),))
        #m.append("pictureliveness=pictureliveness+1")
        m_cols.append("picturetime")
        m_values.append("'{pictureDuration}'")

    if int(statis["videoDuration"]):
        m.append("videotime=videotime+%d" % (int(statis["videoDuration"]),))
        #m.append("videoliveness=videoliveness+1")
        m_cols.append("videotime")
        m_values.append("'{videoDuration}'")

    if int(statis["documentDuration"]):
        m.append("documenttime=documenttime+%d" % (int(statis["documentDuration"]),))
        #m.append("documentliveness=documentliveness+1")
        m_cols.append("documenttime")
        m_values.append("'{documentDuration}'")

    if int(statis["startCount"]):
        m.append("startcount=startcount+%d" % (int(statis["startCount"]),))
        #m.append("openliveness=openliveness+1")
        m_cols.append("startcount")
        m_values.append("'{startCount}'")

    if int(statis["musicDuration"]):
        m.append("musictime=musictime+%d" % (int(statis["musicDuration"]),))
        #m.append("musicliveness=musicliveness+1")
        m_cols.append("musictime")
        m_values.append("'{musicDuration}'")

    if int(statis["baiduLiveness"]):
        m.append("baiduliveness=baiduliveness+1")
        m_cols.append("baiduliveness")
        m_values.append("'{baiduLiveness}'")

    if int(statis["openByOther"]):
        m.append("openbyother=openbyother+%d" % (int(statis["openByOther"]),))
        m_cols.append("openbyother")
        m_values.append("'{openByOther}'")

    if m or m_cols:
        r_date = statis["createTime"]
        sql = u"select id from {mtime_tbl} where terminalid='{terminalId}' and recorddate='{r_date}'"
        s = sql.format(mtime_tbl=mtime_tbl, terminalId = userinfo["terminalId"], r_date = r_date)
        cur.execute(s)
        rs = cur.fetchall()
        if len(rs) > 0:
            m.append("last_update='{last_update}'")
            sql = u"update {mtime_tbl} set %s where terminalid='{terminalId}' and recorddate='{r_date}'" % (",".join(m),)
            s = sql.format(mtime_tbl = mtime_tbl, r_date = r_date, **userinfo)
            cur.execute(s)
            conn.commit()
        else:
            m_cols.append("terminalid")
            m_values.append("'{terminalId}'")
            m_cols.append("last_update")
            m_values.append("'{last_update}'")
            m_cols.append("recorddate")
            m_values.append("'{r_date}'")
            sql = u"insert into {mtime_tbl} (%s) values(%s)" % (",".join(m_cols), ",".join(m_values))
            statis["terminalId"] = userinfo["terminalId"]
            s = sql.format(mtime_tbl=mtime_tbl, r_date = r_date, **statis)
            cur.execute(s)
            conn.commit()

    movie_names = statis["videoNames"]
    names = []

    for v in movie_names:
        watch_time = 0
        filesize = 0
        videolength = ""
        resolution = ""
        if isinstance(v, str) or isinstance(v, unicode):
            parsed = urlparse.urlparse(v)
            u1 = urllib.unquote(parsed.path.encode("utf-8"))
            bname = os.path.basename(u1)
        elif isinstance(v, list):
            if len(v) == 2:
                vname, watch_time = v
            elif len(v) == 5:
                vname, watch_time, filesize, videolength, resolution = v
            parsed = urlparse.urlparse(vname)
            u1 = urllib.unquote(parsed.path.encode("utf-8"))
            bname = os.path.basename(u1)
        t2 = (userinfo["terminalId"], bname, n_time, watch_time, filesize, videolength, resolution)
        names.append(t2)

    if names:
        sql = u"insert into {mname_tbl} (terminalid, videoname, watch_time, duration,filesize,videolength, resolution) values(%s, %s, %s, %s, %s, %s, %s)"
        s = sql.format(mname_tbl = mname_tbl)
        cur.executemany(s, names)
        conn.commit()

    cur.close()

    return json.dumps({"time": statis["createTime"]})
            

def send_msg(msg, users):
    key = "bd1146b4cfa503eb2c1056b693377f30"
    domain = "sip2.simicloud.com"
    port = 50600
    user = "POWER7_webmaster"
    METHOD='MESSAGE'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(5)
    text_tpl="""{method} sip:{to_user}@{domain} SIP/2.0\r\nVia: SIP/2.0/UDP 127.0.0.1;rport;branch=z9hG4bk{branch}\r\nFrom: <sip:{from_user}@{domain}>;tag={tag}\r\nTo: <sip:{to_user}@{domain}>\r\nCall-ID: {callid}\r\nMax-Forwards: 10\r\nContact: <sip:{from_user}@127.0.0.1>\r\nExpires: 20\r\nCSeq: {cseq} {method}\r\nAllow: OPTIONS,INFO,MESSAGE\r\nContent-Type: text/plain\r\nContent-Length: {clen}\r\nUser-Agent: pythonlib/2.7\r\n\r\n{msg}"""

    d = dict(
        method=METHOD,
        to_user="",
        from_user=user,
        domain=domain,
        tag=random_fp.read(10).encode("hex"),
        branch=random_fp.read(10).encode("hex"),
        callid=random_fp.read(5).encode("hex"),
        cseq=int(random_fp.read(1).encode("hex"),16),
        clen=len(msg),
        msg=msg
    )
    for u in users:
        d["to_user"] = u
        text=text_tpl.format(**d)
        #print "send msg to %s" % u
        sock.sendto(rc4(key,text),(domain,port))

    rs_msgs = []
    for i in range(len(users)):
        try:
            data,addr=sock.recvfrom(512)
        except:
            break
        rs_msgs.append(rc4(key,data))
    sock.close()
    oks = []
    fails = []
    for r in rs_msgs:
        fp = StringIO.StringIO(r)
        firstline = fp.readline()
        code = int(firstline.split(" ",2)[1])
        for u in users:
            if u in r:
                #print u,code
                if code == 200:
                    oks.append(u)
                else:
                    fails.append(u)
                break
    for u in users:
        if (u not in oks)  and (u not in fails):
            fails.append(u)
    return oks,fails

def is_login():
    c = request.cookies.get("mloginuid")
    if not c:
        #return redirect("/login")
        return False
    c1 = rc4(cookie_key, base64.b64decode(c))
    if c1.startswith("admin_AUTH"):
        return True
    return False

@app.route("/logout")
def logout():
    next_p=request.values.get("next")
    if not next_p:
        next_p = url_for("push")
    rs=make_response(redirect(next_p))
    rs.set_cookie("mloginuid","")
    return rs

@app.route("/login", methods=["GET", "POST"])
def login():
    username = request.values.get("username")
    passwd = request.values.get("password")
    n = request.values.get("next")
    path = request.values.get("path")
    if not n:
        r1 = request.headers.get("referer")
        if r1:
            n = r1
    if not username or not passwd:
        if not n:
            n="push"
        return render_template("login.html")

    if username == "admin" and passwd == "nimda":
        r =redirect(n) if n else redirect("push")
        rs = make_response(r)
        rs.set_cookie("mloginuid",
                base64.b64encode(rc4(cookie_key, "admin_AUTH_%s" % time.strftime("%Y-%m-%d %H:%M:%S"))),
                max_age=30*24*60,
                path = path if path else "/",
                )
        return rs

    return render_template("login.html", error_msg="login faied")

@app.route("/push", methods=["GET","POST"])
@login_required(next="push")
def push():

    if request.method == "GET":
        conn = get_db2()
        cur = conn.cursor()
        cur.execute("select username from location limit 200")
        res = cur.fetchall()
        cur.close()
        vendors = []
        users = []
        for r in res:
            u = str(r[0])
            v = u.split("_", 1)[0]
            if v not in vendors:
                vendors.append(v)
            users.append(u)
        return render_template("msg_push.html", vendors  = vendors, users = users)
    elif request.method == "POST":
        msg = request.form.get("msg", "")
        if not msg:
            return "no message entered"

        users=request.form.getlist("users")
        if not users:
            return "no users selected"

        oks,fails=send_msg(msg, users)
        return render_template("push_status.html",msg = msg,success = oks, failed = fails)
    else:
        return "400 Bad Request",400

@app.route("/report")
@login_required(next="report")
def report():

    conn = get_db()
    cur = conn.cursor()
    
    t = request.values.get("time","")
    if not t:
        start = time.strftime("%Y-%m-%d %H:00:00", time.localtime(time.time() - 24 * 60 * 60))
        end = time.strftime("%Y-%m-%d %H:%M:%S")
    else:
        end = t
        t1 = time.strptime(t, "%Y-%m-%d %H:%M:%S")
        start = time.strftime("%Y-%m-%d %H:00:00", time.localtime(time.mktime(t1) - 24 * 60 * 60))

    sql = "select count(distinct terminalid) from userinfo where createdate > '%s' and  createdate < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    new_user = int(rs[0][0])

    sql = "select count(distinct terminalid) from mediatimes where last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    active_user = int(rs[0][0])

    sql = "select count(distinct terminalid) from mediatimes where videotime > 0 and last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    video_user = int(rs[0][0])

    sql = "select count(distinct terminalid) from mediatimes where musictime > 0 and last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    music_user = int(rs[0][0])

    sql = "select count(distinct terminalid) from mediatimes where picturetime > 0 and last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    picture_user = int(rs[0][0])

    sql = "select count(distinct terminalid) from mediatimes where documenttime > 0 and last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    document_user = int(rs[0][0])

    sql = "select count(distinct terminalid) from mediatimes where baiduliveness > 0 and last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    baidu_user = int(rs[0][0])

    sql = "select sum(videotime),sum(musictime),sum(documenttime),sum(picturetime),sum(startcount) from mediatimes where last_update > '%s' and  last_update < '%s'" % (start, end)
    cur.execute(sql)
    rs=cur.fetchall()
    videotime,musictime,doctime,picturetime,startcount = rs[0]

    sql = "select count(distinct terminalid) from userinfo where createdate < '%s'" % end
    cur.execute(sql)
    rs=cur.fetchall()
    total_client = rs[0][0]

    sql = "select count(distinct deviceid) from userinfo where createdate < '%s'" % end
    cur.execute(sql)
    rs=cur.fetchall()
    total_dev = rs[0][0]

    sql = "select videoname,count(videoname) as c from movienames where watch_time > '%s' and watch_time < '%s' group by videoname order by c desc limit 10" % (start, end)
    cur.execute(sql)
    rs = cur.fetchall()
    today_favorite_mov =[ (m,t) for (m,t) in rs ]

    sql = "select videoname,count(videoname) as c from movienames where watch_time < '%s' group by videoname order by c desc limit 10" %  (end, )
    cur.execute(sql)
    rs = cur.fetchall()
    total_favorite_mov =[ (m,t) for (m,t) in rs ]

    sql = """select 
        userinfo.terminaltype,count(userinfo.terminaltype) as t, terminalname.friendlyname 
        from userinfo left join terminalname on userinfo.terminaltype = terminalname.terminalname 
        where createdate < '%s' 
        group by userinfo.terminaltype 
        order by t desc
        limit 10
        """ % (end, )
    cur.execute(sql)
    rs = cur.fetchall()
    favorite_dev = [ (m, t, t1) for (m, t, t1) in rs ]

    #sql = """select videoname,duration from movienames where watch_time < '%s' order by duration desc limit 10""" % (end, )
    #cur.execute(sql)
    #rs = cur.fetchall()
    #video_watch  = [ (m, t) for (m, t) in rs ]

    cur.close()

    #tpl = os.path.join(os.path.dirname(__file__), "status_rpt.html")
    return render_template("status_rpt.html", **locals())


@app.route("/fw_update", methods = ["GET", "POST"])
def fw_update():
    sn=request.values.get("sn", "")
    fwver=request.values.get("fwver", "")

    if not sn or not fwver:
        return "Bad Request", 400

    sn = sn.strip()
    fwver = fwver.strip()

    conn = get_db()
    cur = conn.cursor()

    sql = """select 
        devinfo.fwversion, fwinfo.fwversion, fwinfo.fwurl 
        from devinfo left join fwinfo 
        on devinfo.isinternal = fwinfo.isinternal
        where devinfo.serial = '%s'""" % (sn,)
    cur.execute(sql)
    rs = cur.fetchall()

    # serial not exists
    if not rs:
        sql = """insert into devinfo(serial, fwversion, lastupdate) 
        values ('%s', '%s', now())""" % (sn, fwver)
        cur.execute(sql)

        # trust as publict user, check if need update
        sql = "select fwversion, fwurl from fwinfo where isinternal = 0"
        cur.execute(sql)
        rs = cur.fetchall()
        cur.close()
        fwver_1 = rs[0][0].strip()
        p = rs[0][1]
        if fwver_1 != fwver:
            msg = "needupdate:1\r\nfwurl:%s\r\nfwver:%s\r\n" % (p, fwver_1)
        else:
            msg = "needupdate:0\r\nfwurl:\r\nfwver:\r\n"
        return msg,200,{"Content-Type":"text/plain"}

    fw_ver1 = rs[0][1].strip()
    p= rs[0][2].strip()
    fw_ver_n = rs[0][0].strip()

    # check if need update
    if fwver != fw_ver1:
        msg = "needupdate:1\r\nfwurl:%s\r\nfwver:%s\r\n" % (p, fw_ver1)
    else:
        msg = "needupdate:0\r\nfwurl:\r\nfwver:\r\n"

    # update fwversion
    if fw_ver_n != fwver:
        sql = """update  devinfo set fwversion = '%s', lastupdate=now() where serial = '%s'""" % (fwver, sn)
        cur.execute(sql)
        conn.commit()
    cur.close()
    return msg,200,{"Content-Type":"text/plain"}

@app.route("/hello", methods=["GET", "POST"])
@login_required(next="hello")
def hello():
    data = request.stream.read()
    for k,v in request.headers.items():
        data = "%s <br/>\n%s=%s" % (data, k, v)
    for k,v in request.values.items():
        data = "%s <br/>\n%s=%s" % (data, k, v)
    return data,200,{"Content-Type":"text/html","X-P-a":"ccaa"}

@app.route("/hello1/<uid>")
@login_required(next="index")
def index(*args, **kargs):
    return jsonify(a=3,b=4,c=1,d=3)

@app.route("/")
def index2():
    return "ok"

app.debug = True

if __name__ == "__main__":
    #from gevent import monkey
    #monkey.patch_all()
    #from gevent.pywsgi import WSGIServer
    #WSGIServer(('', 8080), application).serve_forever()
    #app.run(port=8080)
    with app.test_request_context():
        print url_for("login", next=url_for("push"))
        print url_for("index",uid=2,c=1)
        print url_for("index2")
